
import { appId, backurl } from '@/config/index'
const href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${backurl}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`

import storage from '@/server/storage.server'
import Api from '@/api/community/index'

const isBind = () => {
  const code = storage.get('code')
  const token = storage.get('token')
  if (code || token) {
    return true
  } else {
    window.location.href = href
  }
}

const getActivityKey = async (key: string) => {
  // 如果有token不去获取了
  let token = storage.get('token') || ''
  if (token) return true

  if (key) {
    try {

      let { code, data } = await Api.getToken({ key })
      if (code == 0) {
        storage.set('token', data)
        return true
      } else {
        return true
      }
    } catch (err) {
      return false
      //
    }
  }
}

// 判断是否登录
const wechatAutoLogin = async (wxcode: string, daV?: string) => {
  if (wxcode) {
    try {
      let { code, data } = await Api.wechatAutoLogin({ wx_grant_code: wxcode, uat_id: daV })
      if (code == 0) {
        storage.set('token', data.token)
        storage.set('userData', data)
        return {
          type: 'toUrl'
        }
        // "未绑定钱包",//当前微信用户未绑定钱包，这是调转到社区h5登录
      } else if (code == 960) {
        storage.set('bangdData', data)
        return {
          type: 'login',
          url: '/communityWeb/login'
        }
        // 未绑定群关系
      } else if (code == 961) {
        storage.set('secret_key', data.secret_key)
        storage.set('uat_id', daV)
        return {
          type: 'login',
          url: '/communityWeb/copy-token'
        }

      }
    } catch (err) {
      //
    }
  }

}

export {
  isBind,
  getActivityKey,
  wechatAutoLogin
}
